<script setup lang="ts">
import {useRouter, useRoute} from 'vue-router'
import type {FormInstance, FormRules, UploadInstance, UploadProps, UploadRawFile} from 'element-plus'
import {genFileId} from 'element-plus'
import HeaderVue from '@/components/Header.vue'
import FooterVue from '@/components/Footer.vue'
import {reactive, ref, h, computed} from 'vue'
import {Server} from '@/stores/ajax';
import {Delete, Download, Plus, ZoomIn} from '@element-plus/icons-vue'
import type {TableColumnCtx} from 'element-plus/es/components/table/src/table-column/defaults'
import type {ElTable} from 'element-plus'
import {Search} from '@element-plus/icons-vue'
import type {UploadFile} from 'element-plus'

import {Delta} from '@vueup/vue-quill'
import MyQuill from '@/components/quillComponent.vue'

import {ServerUtils} from '@/serverUtils';

import {
    format as timeFormat,
} from 'silly-datetime';
import {GetUserState} from "@/stores/userState";
let route = useRoute()
let menuIndex = ref("1")
let firstIn = true
let {query} = route
if (query.chat) {
    menuIndex.value = "1"
}

let user = GetUserState();
let notifications = $ref<any>({total: 0, list: []})

const onMenuSelect = (key: string, keyPath: string[]) => {
    menuIndex.value = key
}
let chatList = ref<any>({})
let lastChattingUser: any = null
let chatSelect = ref(0)
const handleChatChange = (val: number) => {
    lastChattingUser = chatList.value[val].user
}
const refresh = async () => {
    if (user.uid) {
        notifications = await ServerUtils.getNotification(1, 100)
    }
    if (notifications.total) {
        chatList.value = {}
        let newlist = []
        for (let n of notifications.list) {
            switch (n.type) {
                case 'message_to':
                case 'message_from':
                    chatList.value[n.user.uid] ??= {}
                    chatList.value[n.user.uid].chat ??= []
                    chatList.value[n.user.uid].user = n.user
                    chatList.value[n.user.uid].lastTime ??= 1
                    chatList.value[n.user.uid].lastTime =
                        Math.max(chatList.value[n.user.uid].lastTime, n.time)
                    chatList.value[n.user.uid].chat.push(n)
                    break;
                default:
                    newlist.push(n)
                    break;
            }
        }
        notifications.list = newlist
    }
    const chatUid = '' + (query.chat || '')
    if (chatUid) {
        // 第一次聊天
        if (!chatList.value[chatUid]) {
            let user = await ServerUtils.getUserDataById(Number(chatUid), false)
            if (user)
                chatList.value[chatUid] = {user, chat: [], lastTime: Date.now()}
        }
    }
    console.log(chatUid)
    if (firstIn) {
        firstIn = false
        if (chatUid)
            lastChattingUser = chatList.value[chatUid].user
    }
    chatList.value = Object.values(chatList.value).sort((a: any, b: any) => {
        return b['lastTime'] - a['lastTime']
    })
    for (let c in chatList.value) {
        chatList.value[c].chat = chatList.value[c].chat.sort((a: any, b: any) => {
            return a.time - b.time
        })
    }
    if (lastChattingUser) {
        for (let i = 0; i < chatList.value.length; i++) {
            if (chatList.value[i]?.user.uid == lastChattingUser.uid) {
                chatSelect.value = i
                break
            }
        }
    }
}
setTimeout(refresh, 500)
const messageEditor = $ref<any>()
let maxPostWordsLength = 10000
const handleSendMessage = () => {
    ServerUtils.sendMessage(messageEditor,
        chatList.value[chatSelect.value]?.user.uid, 1, maxPostWordsLength).then((v: any) => {
            setTimeout(refresh, 500)
        })
}
</script>

<template>
    <!-- <el-affix style="width: 100%;"> -->
    <header>
        <HeaderVue />
    </header>
    <!-- </el-affix> -->
    <el-container class="notice-block">
        <el-aside width="160px">
            <el-menu default-active="1" class="setting-menu"
                @select="onMenuSelect">
                <el-menu-item index="0" class='fh'>

                    <span>通知</span>
                </el-menu-item>
                <el-menu-item index="1" class='fh'>
                    <span>私信</span>
                </el-menu-item>
            </el-menu>
        </el-aside>
        <el-container>
            <el-main>
                <!-- 通知 {{{ -->
                <div class="fh" v-if="menuIndex == '0'">
                    <div class="fv"
                        style="flex-basis: 800px;">
                        <h2>通知</h2>
                        <div class="fh">
                            <div class="fvs"
                                style="flex-grow: 1;">
                                <el-scrollbar
                                    max-height="600px">
                                    <div class="fvs"
                                        v-for='item in notifications.list'>
                                        <div
                                            style="margin: 10px 0; margin-right: 15px;">
                                            <div class="fv hp"
                                                style="border: 1px black solid; border-radius: 5px;min-height: 70px;min-width: 280px;padding: 10px;">
                                                <div
                                                    style="flex-grow: 1;">
                                                    <p>
                                                        {{
                                                                item.content
                                                        }}
                                                    </p>
                                                </div>
                                                <div class="fontsizes2"
                                                    v-text="timeFormat(item.time, 'YYYY-MM-DD HH:mm:ss')" />


                                            </div>
                                        </div>
                                    </div>
                                </el-scrollbar>
                            </div>
                        </div>
                    </div>

                </div>
                <!-- }}} -->

                <!-- 私信 {{{ -->
                <div class="fhs" v-if="menuIndex == '1'">
                    <div class='message-list'>
                        <el-scrollbar max-height="600px">
                            <el-radio-group class="fvs"
                                style="align-items: flex-start;"
                                @change="handleChatChange"
                                v-model="chatSelect">
                                <el-radio :label="i"
                                    class='user-item'
                                    v-for='(item, i) in chatList'>
                                    {{ item.user.user_name}}
                                </el-radio>
                            </el-radio-group>
                        </el-scrollbar>
                    </div>
                    <div class="fvs message-block"
                        style="flex-grow: 1;">
                        <h3 class='user_name fh'>
                            {{
                                    chatList[chatSelect]?.user.user_name
                            }}
                        </h3>
                        <div class="message-content">
                            <el-scrollbar
                                max-height="360px">
                                <div
                                    v-for='item in chatList[chatSelect]?.chat'>
                                    <div class="my-message fhs"
                                        v-if="item.type == 'message_to'">
                                        <div class='message-text'
                                            v-dompurify-html='item.content' />
                                    </div>
                                    <div v-else
                                        class="others-message fhs">
                                        <div class='message-text'
                                            v-dompurify-html='item.content' />
                                    </div>
                                </div>
                            </el-scrollbar>
                        </div>
                        <div class='message-editor'>
                            <MyQuill theme="snow"
                                content-type="delta"
                                :placeholder="`发送消息 :`"
                                @ready="(e) => {messageEditor = e}" />

                            <!-- {{ editor?.getText()}} {{ content}} -->
                        </div>
                        <el-button class="b-post"
                            @click="handleSendMessage"
                            color="#6666cc">
                            发送
                        </el-button>
                    </div>

                </div>
                <!-- }}} -->

            </el-main>
        </el-container>
    </el-container>

    <div style="height: 20vh;"></div>
    <FooterVue />
</template>

<style lang="scss">
.message-list {
    .user-item {
        .el-radio__input {
            display: none;
        }
    }
}
</style>
<style scoped lang="scss">
.notice-block {
    background-color: white;
    max-width: 960px;
    min-width: 500px;
    margin: 0 auto;

    .setting-menu {
        height: 100%;
    }

    .input-min {
        width: 160px;
        margin-right: 60px;
    }

    .label1 {
        justify-content: end;
        margin-bottom: 10px;
        color: #666;

    }

}

.message-list {
    width: 130px;

    .user-item {}
}

.message-block {
    .user_name {
        color: #666;
    }

    .message-content {
        height: 340px;
        background-color: #f9f9f9;
    }

    .my-message {
        justify-content: end;
    }

    .b-post {
        width: 100px;
        margin-top: 8px;
        align-self: flex-end;
    }

    .message-editor {
        height: 200px;
    }
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.input-search {
    width: 600px;
}

.box-card {
    width: 250px;
}

span {
    display: inline;
}

.avatar-uploader {
    width: 120px;
    height: 120px;
    margin: 0 auto;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    /* transition: var(--el-transition-duration-fast); */
}

.el-upload-list__item-actions {
    position: absolute;
    top: 0;
    line-height: 120px;
    left: 0;
    z-index: 10;
    text-align: center;
    width: 120px;
    color: #0000;
}

@keyframes fadenum {
    0% {
        opacity: 0;
    }

    100% {
        opacity: 1;
    }
}

.el-upload-list__item-actions:hover {
    color: #fff;
    font-weight: 600;
    background-color: #0003;
    animation: fadenum 0.3s 1;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}
</style>
